<template>
  <div class="JSwitch">
    <div
      class="switch_containers"
      :class="openStatus ? 'openStatus' : ''"
      @click="changeStatus"
      :style="openStatus ? getActivityColor : ''"
    >
      <span class="oneItem" :class="!openStatus ? 'activied' : ''">{{
        openText
      }}</span>
      <span class="oneItem" :class="openStatus ? 'activied' : ''">{{
        closeText
      }}</span>
      <span class="slider"></span>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from "vue";
export default {
  props: {
    openText: {
      type: String,
      default: "on",
    },
    closeText: {
      type: String,
      default: "off",
    },
    activeColor: {
      type: String,
      default: "#1aad19",
    },
    status: {
      type: Boolean,
      default: true,
    },
  },
  setup(props, ctx) {
    const openText = ref(props.openText);
    const closeText = ref(props.closeText);
    const activeColor = ref(props.activeColor);
    const openStatus = ref(props.status);
    // ref定义的响应式变量一定要使用 .value才可以使用
    const getActivityColor = computed(() => {
      return `background-color:${activeColor.value};`;
    });

    const changeStatus = () => {
      openStatus.value = !openStatus.value;
      ctx.emit("switchChange", openStatus.value);
      /*
        vue3 触发自定义事件 可以再 setup(props,ctx) 的第二个 ctx参数中获取emit方法触发 
      */
    };

    return {
      openText,
      closeText,
      activeColor,
      openStatus,
      getActivityColor,
      changeStatus,
    };
  },
};
</script>

<style lang="less" scoped>
.switch_containers {
  width: 90px;
  height: 35px;
  background-color: rgb(250, 250, 250);
  display: flex;
  position: relative;
  border-radius: 30px;
  overflow: hidden;
  border: 1px solid #ccc;
  align-items: center;
  transition: all ease-in-out 0.5s;
  cursor: pointer;
  .oneItem {
    width: 50%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    z-index: 20;
    color: rgb(122, 122, 122);
  }
  .slider {
    width: 28px;
    height: 28px;
    position: absolute;
    transition: all ease-in-out 0.5s;
    left: 3px;
    top: 50%;
    transform: translateY(-50%);
    background-color: #1aad19;
    background-color: #fff;
    border-radius: 50%;
    z-index: 10;
    box-shadow: 0 0 5px #ccc;
  }
  .activied {
    // opacity: 0;
    color: #fff;
  }
}

.openStatus {
  background-color: #1aad19;
  > .activied {
    opacity: 0;
  }
  > .oneItem {
    color: #fff;
  }
  > .slider {
    position: absolute;
    left: none;
    transition: all ease-in-out 0.3s;
    left: 57px;
  }
}
</style>